package com.ikkong.common.interceptor;

import javax.servlet.http.HttpServletRequest;

import com.ikkong.common.service.ActiveRecordPluginService;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
import com.jfinal.log.Log;

public class WebsiteInterceptor implements Interceptor {

	private static final Log log=Log.getLog(WebsiteInterceptor.class);
	
	private static final ThreadLocal<String> ME_CONFIGNAME=new ThreadLocal<String>();
	
	public static final String SERVER_NAME="serverName";
	public static final String CONFIG_NAME="configName";

	/**
	 * @Title: 获取访问者的ConfigName
	 * @return String 本次访问的ConfigName
	 */
	public static String getConfigName(){
		return ME_CONFIGNAME.get();
	}
	
	/**
	 * nginx 配置 内容：
	 * location xxxx{
	 * 		proxy_set_header Host $host:80;
	 * 		proxy_set_header X-Forwarded-For $remote_addr;
	 * 		proxy_redirect off;
	 * 		proxy_pass http://1270.0.0.1:8080
	 * 		#配置多台tomcat 就改端口号等
	 * }
	 */
	public void intercept(Invocation inv){
		Controller controller=inv.getController();
		HttpServletRequest request=controller.getRequest();
		
		String ipFromNginx=controller.getHeader("X-Forwarded-For");
		String serverName=request.getServerName();
		/**
		 * 如果数据源是已知固定的   	在启动jfinal的时候，用serverName做数据源的configName 也就是说他们是相等的
		 * String configName=serverName;
		 */
		
		
		/**
		 * 动态管理方式
		 */
		//判断也可以改为
		//if(DbKit.getConfig(configName)!=null){
		String configName=ActiveRecordPluginService.me.getConfigName(serverName);
		controller.setAttr(SERVER_NAME, serverName);
		controller.setAttr(CONFIG_NAME, configName);
		log.debug("访问者:  域名=" + serverName + "  资源K=" + configName + "   IP=" + ipFromNginx);
		if(configName!=null){
			ME_CONFIGNAME.set(configName);
			inv.invoke();
			ME_CONFIGNAME.remove();
		}else{
			controller.renderError(403);
		}
	}
}
